package com.hsy.bibc.modules.waste;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.deparse.dpframe.ui.widget.DPCircleImageView;
import com.deparse.dpframe.utils.DPGsonUtil;
import com.deparse.dpframe.utils.DPHttpUtil;
import com.deparse.dpframe.utils.DPLogUtil;
import com.deparse.dpframe.utils.DPPicassoUtil;
import com.hsy.bibc.R;
import com.hsy.bibc.common.Consts;
import com.hsy.bibc.modules.common.CommitOkActivity;
import com.hsy.bibc.modules.common.CommonBaseActivityWithSimpleActionBar;
import com.hsy.bibc.modules.order.gsondata.OrderIntentJsonData;
import com.hsy.bibc.modules.order.gsondata.w;
import com.hsy.bibc.modules.view.ScrollExpandListView;
import com.hsy.bibc.utils.CommonUtils;
import com.hsy.bibc.utils.HttpUtil;
import com.hsy.bibc.utils.VolleyLoadPicture;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/6/3.
 */
public class WasteConfirmActivity extends CommonBaseActivityWithSimpleActionBar {

    private ScrollExpandListView expand_list;
    private AdapterListView detailGoodsAdapter;
    private OrderIntentJsonData.Result listData;
    private TextView nick_name, score;

    private String type, response;

    private int openGroup = -1;

    private Handler handler = new Handler();
    private DPHttpUtil.HttpCallback httpCallBack = new DPHttpUtil.HttpCallback() {
        @Override
        public void onSuccess(int what, String response) {
            if (0 == what) {
                CommitResultData.Result result = DPGsonUtil.fromJson(response, CommitResultData.Result.class);
                startActivity(CommitOkActivity.class, "1", result.getOrder_id(), result.getOrder_sn());
            }
            CommonUtils.hideProgressDialog();
        }

        @Override
        public void onError(int what, int type, VolleyError error) {
            CommonUtils.hideProgressDialog();
        }

        @Override
        public void onMsgError(int what, int type, String msg) {
            CommonUtils.hideProgressDialog();
        }
    };
    private TextView finish, total_count, total_scores;
    private DPCircleImageView avatar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_waste_confirm);
        total_count = F(R.id.total_count);
        total_scores = F(R.id.total_scores);
        setTitle(R.string.title_confirm);

        type = getActivityStartExtra()[0];
        response = getActivityStartExtra()[1];

//        getContentView().setVisibility(View.GONE);

        expand_list = F(R.id.expand_list);
        finish = F(R.id.finish);

        finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("1".equals(type)) {
                    CommonUtils.showProgressDialog(WasteConfirmActivity.this);
                    Map<String, String> data = new HashMap<>();
                    data.put("token", CommonUtils.getToken(WasteConfirmActivity.this));
                    data.put("data", DPGsonUtil.toJson(listData.getJson()));
                    data.put("uid", listData.getUid());
                    HttpUtil.httpPostWithParams(WasteConfirmActivity.this, 0, Consts.Apis.GET_CONFIRM_FP, data, httpCallBack);
                }
            }
        });

        expand_list.setGroupIndicator(null);

        LayoutInflater inflater = LayoutInflater.from(this);
        View headView = inflater.inflate(R.layout.head_view, null);

        expand_list.addHeaderView(headView);

        nick_name = (TextView) headView.findViewById(R.id.nickname);
        score = (TextView) headView.findViewById(R.id.score);
        avatar = (DPCircleImageView) headView.findViewById(R.id.avatar);

        listData = DPGsonUtil.fromJson(response, OrderIntentJsonData.Result.class);
        nick_name.setText(listData.getUser().getNickname());
        score.setText(listData.getUser().getScore() + "积分");
        total_count.setText("合计" + listData.getOrder_total().getQty() + "件");
        total_scores.setText("共" + listData.getOrder_total().getAmount() + "积分");
//        DPPicassoUtil.with(ConfirmActivity.this).load(listData.getUser().getAvatar()).into(avatar);
        VolleyLoadPicture vlp = new VolleyLoadPicture(WasteConfirmActivity.this, avatar);
        vlp.getmImageLoader().get(listData.getUser().getAvatar(), vlp.getOne_listener());

        detailGoodsAdapter = new AdapterListView(WasteConfirmActivity.this, listData);
        expand_list.setAdapter(detailGoodsAdapter);

        for (int i = 0; i < listData.getOrder().size(); i++) {

            expand_list.expandGroup(0);
            openGroup = 0;
        }

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                expand_list.setSelection(0);
            }
        }, 1000);


        expand_list.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {

                if (openGroup == -1) {
                    expand_list.expandGroup(groupPosition);
                    expand_list.setSelection(groupPosition);
                    openGroup = groupPosition;
                } else if (openGroup == groupPosition) {
                    expand_list.collapseGroup(openGroup);
                    openGroup = -1;
                } else {
                    expand_list.collapseGroup(openGroup);
                    expand_list.expandGroup(groupPosition);
                    expand_list.setSelection(groupPosition);
                    openGroup = groupPosition;
                }
                return true;
            }
        });

//焦点
        expand_list.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {

            @Override
            public void onGroupCollapse(int groupPosition) {
                InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (getWindow().getCurrentFocus() != null) {
                    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    getCurrentFocus().clearFocus();
                }
            }
        });

        expand_list.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {

            @Override
            public void onGroupExpand(int groupPosition) {
                InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (getWindow().getCurrentFocus() != null) {
                    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    getCurrentFocus().clearFocus();
                }
            }
        });

        expand_list.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (getCurrentFocus() != null) {
                    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    getCurrentFocus().clearFocus();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }

        });

    }

    public static class CommitResultData {
        private String error;

        private String msg;

        private Result result;

        public void setError(String error) {
            this.error = error;
        }

        public String getError() {
            return this.error;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }

        public String getMsg() {
            return this.msg;
        }

        public void setResult(Result result) {
            this.result = result;
        }

        public Result getResult() {
            return this.result;
        }

        public static class Result {
            private String order_id;

            private String order_sn;

            public void setOrder_id(String order_id) {
                this.order_id = order_id;
            }

            public String getOrder_id() {
                return this.order_id;
            }

            public void setOrder_sn(String order_sn) {
                this.order_sn = order_sn;
            }

            public String getOrder_sn() {
                return this.order_sn;
            }

        }
    }

    public class AdapterListView extends BaseExpandableListAdapter {
        private List<OrderIntentJsonData.Order> listData;
        private LayoutInflater mInflater;

        public AdapterListView(Context context, OrderIntentJsonData.Result src) {
            listData = src.getOrder();
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        //得到子item需要关联的数据
        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return (listData.get(childPosition).getChildren());
        }

        //得到子item的ID
        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        //设置子item的组件
        @Override
        public View getChildView(final int groupPosition, final int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {
            ChildViewHolder childViewHolder = null;

            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_confirm_order_child, null);

                childViewHolder = new ChildViewHolder();
                childViewHolder.init(convertView);
            } else {
                childViewHolder = (ChildViewHolder) convertView.getTag();
            }
            childViewHolder.setData(listData.get(groupPosition).getChildren().get(childPosition));
            return convertView;
        }

        //获取当前父item下的子item的个数
        @Override
        public int getChildrenCount(int groupPosition) {
            return listData.get(groupPosition).getChildren().size();
        }

        //获取当前父item的数据
        @Override
        public Object getGroup(int groupPosition) {
            return listData.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return listData.size();
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        //设置父item组件
        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {
            convertView = mInflater.inflate(R.layout.item_confirm_order_group, null);
            TextView firstName = (TextView) convertView.findViewById(R.id.groupName);
            firstName.setText(listData.get(groupPosition).getName());

            ImageView parentRightImage = (ImageView) convertView.findViewById(R.id.parentRightImage);
            ImageView parentLeftImage = (ImageView) convertView.findViewById(R.id.parentLeftImage);

            DPPicassoUtil.with(WasteConfirmActivity.this).load(listData.get(groupPosition).getImg()).into(parentLeftImage);
            if (isExpanded) {
                parentRightImage.setRotation(90);
            } else {
                parentRightImage.setRotation(0);
            }
            return convertView;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        public class ChildViewHolder {

            public OrderIntentJsonData.Children src;

            public TextView nameTextView, score;
            public TextView priceTextView;
            public ImageView increaceImageView;
            public TextView valueEditTextExt;
            public ImageView decreaceImageView;
            public TextView unitTextView;
            public TextView showTextView;
            public LinearLayout editAreaLinearLayout;

            public ChildViewHolder() {

            }

            public void init(View convertView) {
                convertView.setTag(this);

                score = (TextView) convertView.findViewById(R.id.score);
                nameTextView = (TextView) convertView.findViewById(R.id.name);
                priceTextView = (TextView) convertView.findViewById(R.id.price);
                increaceImageView = (ImageView) convertView.findViewById(R.id.increace);
                valueEditTextExt = (TextView) convertView.findViewById(R.id.value);
                decreaceImageView = (ImageView) convertView.findViewById(R.id.decreace);
                unitTextView = (TextView) convertView.findViewById(R.id.unit);
                showTextView = (TextView) convertView.findViewById(R.id.show);
                editAreaLinearLayout = (LinearLayout) convertView.findViewById(R.id.edit_area);
            }

            public void setData(OrderIntentJsonData.Children src) {
                if (null == src) {
                    DPLogUtil.e("src = null.");
                    return;
                }
                this.src = src;
                this.nameTextView.setText(src.getName());
//                this.score.setText(src.getScore() + "积分/个");
//                this.priceTextView.setText(src.getPrice() + "元" + "/" + src.getUnit());

                this.valueEditTextExt.setText("×" + String.valueOf(src.getQty()));
//                this.showTextView.setText(String.valueOf(src.getQty()));
            }
        }
    }
}
